import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:flutter/material.dart';

import 'blind_form.dart';
/// 相亲活动
class BlindActiveUi extends StatelessWidget {
  const BlindActiveUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _BlindActiveWidget();
  }
}

class _BlindActiveWidget extends StatefulWidget {
  const _BlindActiveWidget({Key? key}) : super(key: key);

  @override
  State<_BlindActiveWidget> createState() => _BlindActiveWidgetState();
}

class _BlindActiveWidgetState extends State<_BlindActiveWidget> with TickerProviderStateMixin {

  final _titles = ["今日盛典", "未来热门", "往期回顾"];
  late TabController _tabController;
  late PageController _pageController;
  late ScrollController _scrollController;
  late double _itemCoverHeight;
  late double _itemCoverWidth;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _pageController = PageController();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      _numArr[_tabController.index]++;
      _getBlindActives();
    });
  }

  void onTabChanged(int index) {
    _pageController.animateToPage(
        index,
        duration: const Duration(milliseconds: 300),
        curve: Curves.ease
    );
  }

  void onPageChanged(int index) {
    _tabController.animateTo(
      index,
      duration: const Duration(milliseconds: 300)
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _itemCoverWidth = MediaQuery.of(context).size.width - 24;
    _itemCoverHeight = _itemCoverWidth / 351 * 145;
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: buildAppBar(),
      body: Column(
        children: [
          buildTabBar(),
          Expanded(child: buildPageView())
        ],
      ),
    );
  }

  AppBar buildAppBar() {
    return AppBar(
      title: Text(
        "相亲活动",
        style: TextStyle(
          color: ThemeColor.textColor,
          fontSize: 16
        ),
      ),
      centerTitle: true,
      elevation: 0,
      backgroundColor: Colors.white,
      actions: [
        GestureDetector(
          onTap: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const BlindFormUi()));
          },
          child: Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(horizontal: 12),
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: ShapeDecoration(
                color: ThemeColor.mainColor,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16)
                )
            ),
            child: const Text(
              "去发布",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 12
              ),
            ),
          ),
        )
      ],
    );
  }
  
  Widget buildTabBar() {
    return TabBar(
      controller: _tabController,
      tabs: _titles.map((e) => Tab(text: e)).toList(),
      labelColor: ThemeColor.textColor,
      labelStyle: TextStyle(
        color: ThemeColor.textColor,
        fontWeight: FontWeight.bold,
        fontSize: 16
      ),
      unselectedLabelColor: ThemeColor.textColorSecond,
      unselectedLabelStyle: TextStyle(
        color: ThemeColor.textColorSecond,
        fontSize: 14
      ),
      isScrollable: false,
      indicatorColor: ThemeColor.mainColor,
      indicatorSize: TabBarIndicatorSize.label,
      indicatorPadding: const EdgeInsets.symmetric(horizontal: 10),
      onTap: onTabChanged,
    );
  }

  Widget buildPageView() {
    return PageView.builder(
      controller: _pageController,
      physics: const BouncingScrollPhysics(),
      itemCount: _titles.length,
      onPageChanged: onPageChanged,
      itemBuilder: (context, index) {
        return buildListView(_lists[index]);
      },
    );
  }

  Future<void> _onRefresh() async{
    _numArr[_tabController.index] = 1;
    await _getBlindActives();
  }

  Widget buildListView(List list) {
    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: ListView.builder(
          itemCount: list.length,
          itemBuilder: (context, index) {
            return buildItemView(list[index]);
          }
      ),
    );
  }

  Widget buildItemView(itemData) {
    return Container(
      margin: const EdgeInsets.fromLTRB(12, 12, 12, 0),
      child: Column(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.network(
              "https://tse1-mm.cn.bing.net/th/id/R-C.545a6f0a42ee71f647c4515bbaab648b?rik=QWxVJwyCNeb4yQ&riu=http%3a%2f%2fwww.962.net%2fup%2f2016-1%2f201601240912378435102.jpg&ehk=jSiwYRfpv%2fjg7PPtl8qdQMIkPYeCnM25bHONGV8enmQ%3d&risl=&pid=ImgRaw&r=0",
              height: _itemCoverHeight,
              width: _itemCoverWidth,
              fit: BoxFit.cover,
            ),
          ),
          const SizedBox(height: 8,),
          Row(
            children: [
              Expanded(
                child: Text(
                  "这是遗传标题",
                  style: TextStyle(
                    color: ThemeColor.textColor,
                    fontSize: 15
                  ),
                ),
              ),
              Text(
                "45人表明",
                style: TextStyle(
                  color: ThemeColor.textColorSecond,
                  fontSize: 12
                ),
              )
            ],
          ),
          const SizedBox(height: 6,),
          Row(
            children: [
              Expanded(
                child: Text(
                  "北京市朝阳区金拱门大饭店\n01.23 10:00 ~ 01.24 23:59",
                  style: TextStyle(
                    color: ThemeColor.textColorSecond,
                    fontSize: 12,
                    height: 2
                  ),
                ),
              ),
              GestureDetector(
                onTap: () {

                },
                child: Container(
                  height: 24,
                  margin: const EdgeInsets.only(top: 12),
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12)
                    ),
                    color: ThemeColor.mainColor,
                  ),
                  alignment: Alignment.center,
                  child: const Text(
                    "开始报名",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  final _lists = List.generate(3, (index) => <dynamic>[]);
  final _numArr = List.generate(3, (index) => 0);
  _getBlindActives() async {
    final index = _tabController.index;
    String timeType = "";
    if (index == 0) {
      timeType = "TODAY";
    } else if (index == 1) {
      timeType = "TOMORROW";
    } else if (index == 2) {
      timeType = "PAST";
    }
    final res = await Api.getInstance().blindActives(timeType, "", _numArr[index], 10);
    if (res == null) {
      return;
    }
    if (res['data'] == null) {
      return;
    }
    if (res['data']['list'] == null) {
      return;
    }
    List resList = res['data']['list'];
    if (_numArr[index] <= 1) {
      _lists[index].clear();
    }
    setState(() {
      _lists[index].addAll(resList);
    });
  }
}

